package com.toman.ui.work.device;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.itheima.pulltorefreshlib.PullToRefreshBase;
import com.itheima.pulltorefreshlib.PullToRefreshScrollView;
import com.lzy.okhttputils.OkHttpUtils;
import com.toman.Adpter.MyExpandableListPreviewHotAdapter;
import com.toman.Enum.BaseEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.StaticsCount;
import com.toman.JavaBean.TerminalWarmUpDto;
import com.toman.R;
import com.toman.Util.ActionCallback;
import com.toman.Util.DialogUtils;
import com.toman.Util.IntentUtils;
import com.toman.Util.JsonExcludeNull;
import com.toman.Util.StringUtils;
import com.toman.Util.TimeUtil;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.toolbar.ToolBarActivity;
import com.toman.widget.CustomerExpandableListView;
import com.toman.widget.SpaceItemDecoration;
import com.toman.widget.callback.StringLoadingCallback;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import okhttp3.Response;

public class PreviewHotActivity extends ToolBarActivity {


    @BindView(R.id.tv_select0)
    TextView tvSelect0;
    @BindView(R.id.iv_select0)
    ImageView ivSelect0;
    @BindView(R.id.rl_select0)
    RelativeLayout rlSelect0;
    @BindView(R.id.tv_select1)
    TextView tvSelect1;
    @BindView(R.id.iv_select1)
    ImageView ivSelect1;
    @BindView(R.id.rl_select1)
    RelativeLayout rlSelect1;
    @BindView(R.id.tv_select2)
    TextView tvSelect2;
    @BindView(R.id.iv_select2)
    ImageView ivSelect2;
    @BindView(R.id.rl_select2)
    RelativeLayout rlSelect2;
    @BindView(R.id.ll_base)
    LinearLayout llBase;
    @BindView(R.id.btn_all)
    Button btnAll;
    @BindView(R.id.btn_contrary)
    Button btnContrary;
    @BindView(R.id.btn_preview_hot)
    Button btnPreviewHot;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.lv)
    RecyclerView lv;
    @BindView(R.id.mState_refresh)
    PullToRefreshScrollView mStateRefresh;
    @BindView(R.id.mMangeNodata)
    TextView mMangeNodata;
    @BindView(R.id.lv2)
    CustomerExpandableListView lv2;

    private List<TerminalWarmUpDto> list = new ArrayList<TerminalWarmUpDto>();
    private boolean isHot = false;
    CommonAdapter<TerminalWarmUpDto> adapter;
    private ArrayList<ArrayList<TerminalWarmUpDto>> array = new ArrayList<ArrayList<TerminalWarmUpDto>>();
    private ArrayList<String> arrayList = new ArrayList<String>();
    MyExpandableListPreviewHotAdapter adapter2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preview_hot);
        ButterKnife.bind(this);
        initToolBar(BaseEnum.PREVIEWHOT.name);
//        initList();
        initView();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!StringUtils.isEmpty(getIntent().getStringExtra("status"))) {
            setStatus(getIntent().getStringExtra("status"));
        }
        else {setStatus("0");}

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_setting, menu);

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_setting:
                        IntentUtils.startActivity(PreviewHotActivity.this,PreviewHotConfigActivity.class);
                        break;
                }
                return false;
            }
        });

        return true;
    }
    private void initView() {
        mStateRefresh.setMode(PullToRefreshBase.Mode.PULL_DOWN_TO_REFRESH);
        mStateRefresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                //getHttp(1,1);
//                content1=content2=content3=content4=null;
                dialog = null;
                dialogList.clear();
                page = 2;
                customer(1, 1, "");


            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
//                customer(page, 2, "");
//                page += 1;


            }
        });



        adapter2 = new MyExpandableListPreviewHotAdapter(this, arrayList, array);


        initAdapter();
        lv.setAdapter(adapter);
        lv2.setAdapter(adapter2);
        GridLayoutManager mgr = new GridLayoutManager(this, 3);
        lv.setLayoutManager(mgr);
        lv.addItemDecoration(new SpaceItemDecoration(20, 3));

    }

    @OnClick({R.id.btn_all, R.id.btn_contrary, R.id.btn_preview_hot, R.id.rl_select0, R.id.rl_select1, R.id.rl_select2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_all:
                if (isHot){
                    adapter2.selectAll();
                }
else {                for (TerminalWarmUpDto entity : list) {
                    entity.setSelected(true);
                }
                adapter.notifyDataSetChanged();}
                break;
            case R.id.btn_contrary:
                if (isHot){
                    adapter2.selectContrary();
                }
               else{ for (TerminalWarmUpDto entity : list) {
                    entity.setSelected(!entity.isSelected());
                }
                adapter.notifyDataSetChanged();}
                break;
            case R.id.btn_preview_hot:
                if (isHot) {
                    if (ViewUtil.getPreviewHot(adapter2.getSelectedList()) == null) {
                        ToastUtil.makeText(getApplicationContext(), "请至少选中一个选项");
                    }
                    else {
                        DialogUtils.mutiCheckDialog(this, "设备", "关闭预热", NewBaseUrl.management_warmupterminal_stop, "terminalIds",ViewUtil.getPreviewHot(adapter2.getSelectedList()), new ActionCallback() {
                            @Override
                            public void run() {
                                setStatus("0");
                            }
                        });
                    }
                } else if (ViewUtil.getPreviewHot(list) == null) {
                    ToastUtil.makeText(getApplicationContext(), "请至少选中一个选项");
                }  else {
                    DialogUtils.mutiCheckDialog(this, "设备", "预热", NewBaseUrl.management_warmupterminal_warm, "terminalIds", ViewUtil.getPreviewHot(list), new ActionCallback() {
                        @Override
                        public void run() {

                            setStatus("1");
                        }
                    });

                }

                break;

            case R.id.rl_select0:
                setStatus("0");
                break;
            case R.id.rl_select1:
                setStatus("1");
                break;
            case R.id.rl_select2:
                setStatus("2");
                break;
        }

    }

    private void setStatus(String status) {
        this.status = status;
        switch (status) {
            case "0":
                isHot = false;
                tvSelect0.setTextColor(getResources().getColor(R.color.button_blue));
                tvSelect1.setTextColor(getResources().getColor(R.color.black33));
                tvSelect2.setTextColor(getResources().getColor(R.color.black33));
                ivSelect0.setBackgroundColor(getResources().getColor(R.color.button_blue));
                ivSelect1.setBackgroundColor(getResources().getColor(R.color.white));
                ivSelect2.setBackgroundColor(getResources().getColor(R.color.white));
                btnPreviewHot.setText("预热");
//                mStateRefresh.setVisibility(View.VISIBLE);
//                mStateRefresh2.setVisibility(View.GONE);
                customer(1, 1, "");
                break;
            case "1":
                isHot = true;
                tvSelect1.setTextColor(getResources().getColor(R.color.button_blue));
                tvSelect2.setTextColor(getResources().getColor(R.color.black33));
                tvSelect0.setTextColor(getResources().getColor(R.color.black33));
                ivSelect1.setBackgroundColor(getResources().getColor(R.color.button_blue));
                ivSelect2.setBackgroundColor(getResources().getColor(R.color.white));
                ivSelect0.setBackgroundColor(getResources().getColor(R.color.white));
                btnPreviewHot.setText("关闭预热");
//                mStateRefresh.setVisibility(View.GONE);
//                mStateRefresh2.setVisibility(View.VISIBLE);
                customer(1, 1, "");
                break;
            case "2":
                tvSelect2.setTextColor(getResources().getColor(R.color.button_blue));
                tvSelect1.setTextColor(getResources().getColor(R.color.black33));
                tvSelect0.setTextColor(getResources().getColor(R.color.black33));

                ivSelect2.setBackgroundColor(getResources().getColor(R.color.button_blue));
                ivSelect1.setBackgroundColor(getResources().getColor(R.color.white));
                ivSelect0.setBackgroundColor(getResources().getColor(R.color.white));
                customer(1, 1, "");


                break;

        }
    }

    private void initAdapter() {
        adapter = new CommonAdapter<TerminalWarmUpDto>(this, R.layout.item_preview_hot_card, list) {
            @Override
            protected void convert(ViewHolder holder, TerminalWarmUpDto item, final int position) {
                CardView cv = holder.getView(R.id.cv);
                RelativeLayout rl_select = holder.getView(R.id.rl_select);
                TextView tv_time = holder.getView(R.id.tv_time);
                holder.setText(R.id.tv_terminal_num, item.getTerminalNum());
                holder.setText(R.id.tv_beltline, item.getBeltlineName());
                if (item.getDeviceName() == null) {
                    holder.getView(R.id.tv_output).setVisibility(View.INVISIBLE);
                } else {
                    holder.setText(R.id.tv_output, item.getDeviceName());
                }
                if (item.isSelected()) {
                    rl_select.setVisibility(View.VISIBLE);
                } else {
                    rl_select.setVisibility(View.GONE);
                }
                ImageView iv_status = holder.getView(R.id.iv_status);
                if (item.getOnlineStatus() == 1) {
                    iv_status.setImageResource(R.mipmap.cxxj_icon_online);
                } else {
                    iv_status.setImageResource(R.mipmap.cxxj_icon_offline);
                }

                if (item.getBeltlineStatus() == null) {
                    cv.setCardBackgroundColor(mContext.getResources().getColor(R.color.beltline_gray));
                } else {
                    switch (item.getWarmUpStatus()) {
                        case "2":
                            cv.setCardBackgroundColor(mContext.getResources().getColor(R.color.hot_red));
                            tv_time.setVisibility(View.VISIBLE);

                            tv_time.setText(TimeUtil.convert2min(item.getWarmUpTime()));
                            break;
                        case "1":
                            cv.setCardBackgroundColor(mContext.getResources().getColor(R.color.hot_gray));
                            tv_time.setVisibility(View.GONE);
                            break;

                    }
                }
            }
        };
        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                RelativeLayout rl_select = view.findViewById(R.id.rl_select);
                ViewUtil.hideView(rl_select);
                TerminalWarmUpDto bean = list.get(position);
                bean.setSelected(!bean.isSelected());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

    }


    public void customer(Integer page, final Integer type, String search) {
//        if (dialog != null) {
//            dialog.dismiss();
//        }
//        mStateRefresh.setRefreshing();
        OkHttpUtils
                .get(NewBaseUrl.management_warmupterminal_list)
                .headers("token", token)
                .params("companyId", mCompanyId)
                .params("key", search)
                .params("limit", "1000")
                .params("page", page.toString())
                .execute(new StringLoadingCallback(this, mStateRefresh, search) {


                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "预热: " + result);

                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());
                        if (type == 1) {
                            list.clear();
                        }
                        if (code == 0) {
                            JSONObject Jpage = jsonObj.getJSONObject("page");

                            List<TerminalWarmUpDto> jsonArray = new ArrayList<TerminalWarmUpDto>(JsonExcludeNull.parseArrayExcludeNull(Jpage.getString("list"), TerminalWarmUpDto.class));


//                            预热中
                            if (isHot) {
                                lv.setVisibility(View.GONE);
                                lv2.setVisibility(View.VISIBLE);
                                array.clear();
                                arrayList.clear();
                                JSONObject jsonObject = Jpage.getJSONObject("exResults");
                                ArrayList<TerminalWarmUpDto> warningList = new ArrayList<TerminalWarmUpDto>(JsonExcludeNull.parseArrayExcludeNull(jsonObject.getString("warningList"), TerminalWarmUpDto.class));
                                ArrayList<TerminalWarmUpDto> toBeCheckedList = new ArrayList<TerminalWarmUpDto>(JsonExcludeNull.parseArrayExcludeNull(jsonObject.getString("toBeCheckedList"), TerminalWarmUpDto.class));
                                ArrayList<TerminalWarmUpDto> onList = new ArrayList<TerminalWarmUpDto>(JsonExcludeNull.parseArrayExcludeNull(jsonObject.getString("onList"), TerminalWarmUpDto.class));
                                ArrayList<TerminalWarmUpDto> okList = new ArrayList<TerminalWarmUpDto>(JsonExcludeNull.parseArrayExcludeNull(jsonObject.getString("okList"), TerminalWarmUpDto.class));
                               if (warningList.size()!=0){
                                   arrayList.add("报警");
                                   array.add(warningList);
                               }
                                if (toBeCheckedList.size()!=0){
                                    arrayList.add("待检查");
                                    array.add(toBeCheckedList);
                                }
                                if (onList.size()!=0){
                                    arrayList.add("正常预热（待机）");
                                    array.add(onList);
                                }
                                if (okList.size()!=0){
                                    arrayList.add("正常预热（空转）");
                                    array.add(okList);
                                }
if (array.size()==0){
    mMangeNodata.setVisibility(View.VISIBLE);
}
else {
    mMangeNodata.setVisibility(View.GONE);

}
adapter2.refreshList();
adapter2.notifyDataSetChanged();
                                for (int i=0; i<arrayList.size(); i++)
                                {
                                    lv2.expandGroup(i);
                                };

                            }
//                            可预热
                            else {
                                lv.setVisibility(View.VISIBLE);
                                lv2.setVisibility(View.GONE);
                                for (TerminalWarmUpDto bean : jsonArray) {
                                    if (bean.getWarmUpStatus() != null) {
                                        if (bean.getWarmUpStatus().equals("1")) {
                                            list.add(bean);
                                        }
                                    }
                                }
                                if (list.size() == 0) {
                                    mMangeNodata.setVisibility(View.VISIBLE);
                                } else {
                                    mMangeNodata.setVisibility(View.GONE);
                                }
                                adapter.notifyDataSetChanged();
                            }


                            mStateRefresh.onRefreshComplete();

                            StaticsCount count = JSON.parseObject(Jpage.getString("staticsCount"), new TypeReference<StaticsCount>() {
                            });
                            tvSelect0.setText("可预热(" + count.getCount0() + ")");
                            tvSelect1.setText("预热中(" + count.getCount1() + ")");

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

//                        mPullToRefreshScrollView.onRefreshComplete();
                    }
                });
    }


}
